#include "stdafx.h"
#include <stdio.h>
#include "SockekClient.h"
#include "PacketAnalyzer.h"
#include <malloc.h>
#include "PipeClient.h"

#define D_BUFFER_MAX_LENGTH (1024*1024*10)

struct PipeClientCtrl
{
	char rcv_buffer[D_BUFFER_MAX_LENGTH];
	char snd_buffer[D_BUFFER_MAX_LENGTH];
	int buf_max_size;
	SocketConnectionHandle socket_handle;
	PacketAnalyzController pack_anlz;
	PacketAnalyzController *pPackCtrl;
};

EXTERN_C
{
	TRADEAGENTCLIENTDLL_API PipeClientHandle __stdcall PipeClientInit(char* ipAddressStr, int port)
	{
		printf("Init Connection Client.ip=%s:%d\n", ipAddressStr, port);
		PipeClientHandle handle = (PipeClientHandle)malloc(sizeof(PipeClientCtrl));
		
		handle->socket_handle = SocketClient_Create();
		SocketClient_Connect(handle->socket_handle, ipAddressStr, port);
		
		PacketAnalyzerInit(&handle->pack_anlz);
		handle->pPackCtrl = &handle->pack_anlz;
		handle->buf_max_size = D_BUFFER_MAX_LENGTH;

		return handle;
	}
	TRADEAGENTCLIENTDLL_API void __stdcall PipeClientClose(PipeClientHandle handle)
	{
		printf("CloseConnection \n");
		SocketClient_Close(handle->socket_handle);
		PacketAnalyzerClose(&handle->pack_anlz);
		return;
	}

	TRADEAGENTCLIENTDLL_API int __stdcall PipeClientGetPacket(PipeClientHandle handle, PacketReaderHandle *pack)
	{
		int rcvBufLen;
		int rcvCount, ret;
		Packet packet;
		*pack = NULL;
		while (true)
		{
			rcvBufLen = handle->buf_max_size;
			rcvCount = SocketClient_Reveice(handle->socket_handle, handle->rcv_buffer, &rcvBufLen);
			if (rcvCount <= 0)
				break;
			// printf("Get data,len=%d.\r\n", rcvBufLen);
			ret = PacketAnalyzerAddData(handle->pPackCtrl, handle->rcv_buffer, rcvBufLen, &packet);
			if (ret == 0)
			{
				// printf("Packet get continue.\r\n");
				continue;
			}

			// Get packet
			printf("Get one packet!.\r\n");
			*pack = PacketReaderCreate(packet);

			return 1;
		}

		return -1;
	}

	TRADEAGENTCLIENTDLL_API int __stdcall PipeClientSendPacket(PipeClientHandle handle, PacketWriterHandle pack)
	{
		Packet packet;
		int sndLen, ret;
		char *pSndBuf = NULL;

		PacketWriterGetPacket(pack, &packet);
		PacketAnalyzerSetHeader(&packet, &pSndBuf, &sndLen);
		ret = SocketClient_Send(handle->socket_handle, pSndBuf, sndLen);
		return ret;
	}
}